<template>
  <div class="loginContainer">
    <div class="closeWrapper">
      <span class="iconfont iconicon-test" @click="$router.push('/')"></span>
      <div class="register" @click="$router.push('/register')">注册</div>
    </div>
    <div class="logoWrapper">
      <span class="iconfont iconnew"></span>
    </div>
    <van-form class="loginForm">
      <!-- rule是用来定义规则的意思 -->
      <comField label="手机号" placeholder="手机号" :rules="[{ required: true, message: '请填写手机号' }]" type="number" :rule="ruleUsername" @valChanged="setUsername" />
      <comField label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" type="text" :rule="rulePassword" @valChanged="setPassword" />
      <comButton @clicked="login" btnText="登陆" />
    </van-form>
  </div>
</template>

<script>
import comField from '../components/comField.vue'
import comButton from '../components/comButton.vue'
export default {
  components: {
    comField,
    comButton
  },
  data() {
    return {
      username: '',
      password: '',
      // 定义规则,这里用了一个正则表达式
      ruleUsername: '^\\d{5,11}$',
      rulePassword: '^.{3,9}$'
    }
  },
  methods: {
    // 每当数据变化,应该通知父组件
    setUsername(username) {
      this.username = username
    },
    setPassword(password) {
      this.password = password
    },
    login() {
      // 当用户名或者密码有一项为空时,阻止继续操作
      if (!this.username || !this.password) {
        // this.$toast.fail('请输入完整信息')
        // 弹窗以后阻止继续操作, return
        return
      }
      // 数据的校验
      var regExpUsername = new RegExp(this.ruleUsername)
      if (!regExpUsername.test(this.username)) {
        this.$toast.fail('用户名格式错误')
        return
      }

      var regExpPassword = new RegExp(this.rulePassword)
      if (!regExpPassword.test(this.password)) {
        this.$toast.fail('密码格式错误')
        // 弹窗以后阻止继续操作, return
        return
      }

      this.$axios({
        url: '/login',
        method: 'post',
        data: {
          username: this.username,
          password: this.password
        }
      }).then(res => {
        console.log(res)

        // eslint-disable-next-line no-unused-vars
        const { message, data } = res.data

        if (message === '登录成功') {
          localStorage.setItem('token', data.token)
          localStorage.setItem('userId', data.user.id)
          this.$toast.success(message)
          this.$router.push('/home')
        } else {
          this.$toast.fail(message)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.closeWrapper {
  padding: 4.4444vw 4.4444vw;
  display: flex;
  align-items: center;

  .iconicon-test {
    font-size: 7.5vw;
    flex: 1;
  }
  .register {
    font-size: 3.8889vw;
    border: 1px solid #888;
    padding: 2.7778vw;
    border-radius: 2.7778vw;
  }
}
.logoWrapper {
  text-align: center;
  color: #d81e06;
  .iconnew {
    font-size: 35vw;
  }
}
</style>
